package com.frogs.ucenter.v1.service.impl;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.frogs.api.wechat.util.SendMessageUtil;
import com.frogs.framework.util.PageList;
import com.frogs.framework.util.date.DateUtil;
import com.frogs.system.util.MessageActionKey;
import com.frogs.system.util.OpenPlatformEnum;
import com.frogs.system.web.api.request.Request;
import com.frogs.system.web.api.response.Response;
import com.frogs.ucenter.component.RequestApiHelper;
import com.frogs.ucenter.dao.UserRemindedInfoDao;
import com.frogs.ucenter.dao.WechatUserBaseInfoDao;
import com.frogs.ucenter.entity.UserRemindedInfo;
import com.frogs.ucenter.entity.WechatUserBaseInfo;
import com.frogs.ucenter.v1.request.UserRemindedInfoAddRequest;
import com.frogs.ucenter.v1.response.AddResponse;
import com.frogs.ucenter.v1.service.UserHonorService;
import com.frogs.ucenter.v1.service.UserRemindedInfoService;
import com.frogs.ucenter.v1.util.ApiConstants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service(ApiConstants.VERSION+"userRemindedInfoService")
public class UserRemindedInfoServiceImpl implements UserRemindedInfoService{
	private static final Logger log = LoggerFactory.getLogger(UserRemindedInfoServiceImpl.class);

	@Resource
	private UserRemindedInfoDao userRemindedInfoDao;
	@Resource
	private WechatUserBaseInfoDao wechatUserBaseInfoDao;
	@Resource
	private UserHonorService userHonorService;
	@Resource
	private RequestApiHelper requestApiHelper;
	
	@Override
	public Response doRtemind(Request request) throws Exception {
		AddResponse<UserRemindedInfo> response = new AddResponse<UserRemindedInfo>();
		try {
			UserRemindedInfoAddRequest addRequset = (UserRemindedInfoAddRequest)request;
			int openPlatformId = addRequset.getOpenPlatformId();
			Map<String,Object> params = new HashMap<String , Object>();
			params.put("eqUserId", addRequset.getUserId());
			params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
			PageList<WechatUserBaseInfo> userList = wechatUserBaseInfoDao.selectByMap(params, 1, 1);
			WechatUserBaseInfo wechatUserBaseInfo = userList.get(0);
			String nickName = wechatUserBaseInfo.getNickName();
			params.clear();
			params.put("eqUserId", addRequset.getFollowedUserId());
			params.put("eqWechatApplicationId", OpenPlatformEnum.WECHAT_HDC.getId());
			userList = wechatUserBaseInfoDao.selectByMap(params, 1, 1);
			wechatUserBaseInfo = userList.get(0);
			String openId = wechatUserBaseInfo.getOpenId();
			this.sendWechatMsg(openId, nickName, addRequset.getDay(), addRequset.getContent(), openPlatformId);
			UserRemindedInfo userRemindedInfo = new UserRemindedInfo();
			userRemindedInfo.setInitiateUserId(addRequset.getUserId());
			userRemindedInfo.setReceiveUserId(addRequset.getFollowedUserId());
			userRemindedInfo.setTypeId(addRequset.getDataType());
			userRemindedInfo.setOpenPlatformId(openPlatformId);
			userRemindedInfo.setMessage(addRequset.getMessage()); 
			userRemindedInfoDao.insert(userRemindedInfo);
			
			
			response.setInfo(userRemindedInfo);
			response.setTip("提醒成功");
		} catch (Exception e) {
			log.error("func[{}] request[{}] exception[{}] desc[fail]",
					new Object[] { this.getClass().getName() +"."+Thread.currentThread().getStackTrace()[1].getMethodName(),
						request,Arrays.deepToString(e.getStackTrace()) });
		}
	    return response;
	}
	
	private void sendWechatMsg(String openId, String nickName, Integer day, String dataName, Integer openPlatformId) {
		String dataSingle = "{\"keyword1\": {\"value\":\"time\",\"color\":\"#173177\"},"
				+ "\"keyword2\": {\"value\":\"content\",\"color\":\"#173177\"}}";
		
		//模板id
		String templateId = "cO_3acLQ0L5Ihm1lso9K4T9UPV8kVt8-YOCPqXCWMZk";
		//提醒对应的跳转链接（记得改）
		String url = "https://open.weixin.qq.com/connect/oauth2/authorize?&redirect_uri=http%3A%2F%2Fw.frogshealth.com%2Fuser%2Fdata%2Ftoday.html%3facType%3d"+MessageActionKey.PROMPT_LOG.getId()+"&appid=wxb30222354415be84&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
		//头部颜色
		String topcolor = "#FF0000";
		
		//给自己提醒
		String data = "";
		if (!"计步".equals(dataName)) {
			data = dataSingle.replace("time", DateUtil.formatDate(new Date(), "yyyy年MM月dd日 HH:mm"))
					.replace("content","您的家人（"+nickName+"）提醒您："+(day == 0 ? ("你还没测量过"+dataName) : ("你有"+day+"天未测量"+dataName+"了"))+"，别忘了按时测量！");
		} else {
			data = dataSingle.replace("time", DateUtil.formatDate(new Date(), "yyyy年MM月dd日 HH:mm"))
					.replace("content", "您的家人（"+nickName+"）提醒您今天的运动量不足，多运动将有助于身体健康，还能提升家庭繁荣度，加油哦！");
		}
		
		String content="{\"touser\":\""+openId+"\",\"template_id\":\""+templateId+"\",\"url\":\""+url+
				"\",\"topcolor\":\""+topcolor+"\",\"data\":"+data+"}";
		JSONObject jsonObject = SendMessageUtil.sendTemplatMessage(requestApiHelper.getAccessToken(openPlatformId), content);
		log.info("func[sendWechatMsg] result[" + jsonObject + "] desc[get send result]");
	}

}
